package com.lmq.backend.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lmq.backend.mapper.BotMapper;
import com.lmq.backend.pojo.Bot;
import com.lmq.backend.service.impl.utils.UserDetailsImpl;
import com.lmq.backend.service.user.account.InfoService;
import com.lmq.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class InfoServiceImpl implements InfoService {

    @Autowired
    private BotMapper botMapper;

    @Override
    public Map<String, String> getInfo() {

        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();


        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        Map<String, String> map = new HashMap<>();
        map.put("message", "success");
        map.put("id", user.getId().toString());
        map.put("username", user.getUsername());
        map.put("photo", user.getPhoto());

        QueryWrapper<Bot> bots = new QueryWrapper<>();
        bots.eq("user_id", user.getId());
        List<Bot> botList = botMapper.selectList(bots);

        if(botList.isEmpty()) {
            Date now = new Date();
            Bot bot = new Bot(null, user.getId(), "官方Bot", "Cell x y\n" + "g, sx, asy, bsx, bsy", "public Integer nextMove(String input) {\n" +
                    "\n" +
                    "  getData(input);\n" +
                    "\n" +
                    "  for(Cell c: aCells) g[c.x][c.y] = 1;\n" +
                    "  for(Cell c: bCells) g[c.x][c.y] = 1;\n" +
                    "\n" +
                    "  int[] dx = {-1, 0, 1, 0}, dy = {0, 1, 0, -1};\n" +
                    "  for(int i = 0; i < 4; i ++ ) {\n" +
                    "    int x = aCells.get(aCells.size() - 1).x + dx[i];\n" +
                    "    int y = aCells.get(aCells.size() - 1).y + dy[i];\n" +
                    "    if (x >= 0 && x < 13 && y >= 0 && y < 14 && g[x][y] == 0) {\n" +
                    "      return i;\n" +
                    "    }\n" +
                    "  }\n" +
                    "  return 0;\n" +
                    "}", now, now);

            botMapper.insert(bot);
        }

        return map;
    }
}
